using System.Linq;

namespace Comteck.Ktt.Services.SeedData {
  /// <summary>
  /// 强制更新打印模板：确保按自提点排序和五角星标记正常工作
  /// </summary>
  public class _20250112002_ForceUpdatePrintTemplate : IDataSeed {
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void Init(AppDbContext context) {
      // 强制更新所有订单打印模板的SQL排序
      var allPrintTemplateData = context.PrintTemplateData
        .Where(x => x.Name == "table0" && 
                   (x.Sql.Contains("saleorder") || x.Sql.Contains("SaleOrder")) && 
                   x.Sql.Contains("@ids"))
        .ToList();
      
      bool hasChanges = false;
      
      foreach (var templateData in allPrintTemplateData) {
        // 检查是否已经是正确的排序
        if (!templateData.Sql.Contains("order by selforgname, recipientaddress")) {
          // 更新为正确的排序
          if (templateData.Sql.Contains("order by")) {
            // 替换现有的排序
            var orderByIndex = templateData.Sql.IndexOf("order by");
            templateData.Sql = templateData.Sql.Substring(0, orderByIndex) + "order by selforgname, recipientaddress";
          } else {
            // 添加排序
            templateData.Sql += " order by selforgname, recipientaddress";
          }
          hasChanges = true;
        }
      }
      
      if (hasChanges) {
        context.SaveChanges();
      }
    }
  }
}